package com.competition.controller;

import com.UpYun;

import com.competition.resp.ResponseResult;
import com.competition.utils.ImageUrl;
import com.upyun.UpException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${yBucketName}")
    private String yBucketName;
    @Value("${yUserName}")
    private String yUserName;
    @Value("${yPassword}")
    private String yPassword;
    @Value("${yCatalogue}")
    private String yCatalogue;

    //上传图片-又拍云
    @RequestMapping("/uploadImage")
    @ResponseBody
    public ResponseResult uploadImg(@RequestParam("file") MultipartFile file, String uploadPath, String suffix) throws IOException, UpException {
//        参数1：你创建的服务名称；参数二：你创建的操作员名称；参数三：你创建操作员生成的密码。
//        UpYun upYun = new UpYun("job-imags", "dream", "GoANPm05VpUcsl4MpG9fL4PFVSBoxdH3");
        UpYun upYun = new UpYun(yBucketName, yUserName, yPassword);
        System.out.println(yBucketName+":"+yUserName+":"+yPassword);
//        file.getOriginalFilename()是图片原来的名称
//        String filename = file.getOriginalFilename()+ UUID.randomUUID().toString()+"."+suffix;
        String filename = UUID.randomUUID().toString()+"."+suffix;
        System.out.println("图片名称："+filename);
        try{
            boolean re = upYun.writeFile(yCatalogue+uploadPath+"/"+filename,file.getBytes(),false);
        }catch (IOException i){
            return new ResponseResult(500,"文件读取失败",filename);
        }catch (UpException u){
            return new ResponseResult(500,"文件上传失败",filename);
        }
        return new ResponseResult(200,"文件上传成功",filename);
    }

    //又拍云删除图片
    @RequestMapping("/deleteImg/{uploadPath}/{fileName}")
    @ResponseBody
    public ResponseResult deleteImg(@PathVariable("uploadPath") String uploadPath, @PathVariable("fileName") String fileName){
        //        参数1：你创建的服务名称；参数二：你创建的操作员名称；参数三：你创建操作员生成的密码。
//        UpYun upYun = new UpYun("job-imags", "dream", "GoANPm05VpUcsl4MpG9fL4PFVSBoxdH3");
        UpYun upYun = new UpYun(yBucketName, yUserName, yPassword);
        Boolean result = null;
        System.out.println(yCatalogue + uploadPath + "/" + fileName);
        try{
            result = upYun.deleteFile(yCatalogue + uploadPath + "/" + fileName);
       }
        catch (IOException i){
            return new ResponseResult(500,"文件读取失败",result);
        }catch (UpException u){
            return new ResponseResult(500,"文件删除失败",result);
        }

        return new ResponseResult(200,"文件删除成功",result);
    }




}
